package com.example.demo.services;

import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.dao.mapper.UserMapper;
import com.example.demo.dao.repository.UserRepository;
import com.example.demo.entity.Users;

/**
 * @author Buer
 * @update 2021/4/25/02510:29
 */
@Component
public class WeChatLogin {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserMapper userMapper;

    /*JSON数据包，验证用户名和密码*/
    public String firstLogin(JSONObject info) {
        System.out.println("后端收到 info->" + info);
        // 创建实体类对象
        Users user = new Users();
        // 验证是否有该用户
        int hasId = userMapper.selectIdIsNull(info.getString("userId"));
        if (hasId == 0) {
            return "用户id错误->" + info.getString("userId");
        }
        // 验证账号、密码的正常性
        user = userRepository.findByIdAndPassword(info.getString("userId"), info.getString("userPassword"));
        if (Objects.equals(String.valueOf(user), "null")) {
            return "密码错误->" + info.getString("userPassword");
        }
        System.out.println("获取到用户信息->" + user.toString());
        return JSONObject.toJSONString(user);
    }

    /*存储imageUrl*/
    public Boolean setImage(JSONObject info) {
        // 存储图片信息
        int isSuccess = userMapper.updateImage(info.getString("userId"), info.getString("avatarUrl"));
        // 判断存储操作
        if (isSuccess == 0) {
            System.out.println("用户头像存储失败->" + info.getString("userId"));
        }
        return isSuccess == 1;
    }

    /*二次登录校验*/
    public Boolean isVerify(String token) {
        // 验证token有效性
        int hasToken = userMapper.selectIdIsNull(token);
        if (hasToken == 0) {
            System.out.println("token验证失败->" + token);
        } else {
            System.out.println("token验证成功->" + token);
        }
        return hasToken == 1;
    }
}
